#!/usr/bin/env python2.7

import optparse
import os
import sys

import jinja2

from venya.lib import stdlib, cmdparser, exception

import aclparser

class acl(cmdparser.GetOpt):
    option_list = (
            optparse.make_option("-f", "--filename", type = "str",
                help = "Config file", dest = "filename"),
    ) + cmdparser.GetOpt.option_list

    help = """

    ACL Gen"
    """

    usage = "[ options ] file"

    @cmdparser.getopts
    def handle(self):
        config = None
        if self.options.filename:
            if os.path.exists(self.options.filename):
                config = aclparser.parse_config(self.options.filename)
            else:
                self.error("%s does NOT exist", self.options.filename)
        else:
            self.error("no filename defined!")

        if config:
            items = {}
            items["header"] = config.header
            items["terms"] = config.terms
            items["first"] = True
            options = {}
            template = "firewall.j2"
            jenv = jinja2.Environment(
                    extensions = [ 'jinja2.ext.do' ],
                    loader = jinja2.FileSystemLoader(os.path.dirname(".")),
                    keep_trailing_newline = True,
                    lstrip_blocks = True,
                    trim_blocks = True)
            tmpl = jenv.get_template(template)
            print(tmpl.render(items))

if __name__ == "__main__":
    instance =  None
    try:
        instance = acl(version = 0.1, args = sys.argv)
        if instance.length <= 1:
            instance.printhelp()
        else:
            instance.handle()
    except exception.GetOptError as err:
        print(err)
        sys.exit(1)

